<?php

namespace App\Http\Controllers;

use App\Services\GraspService;
use App\Services\WechatService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class CheckController extends Controller {

    public function token($user_id)
    {
        return GraspService::getDzyHeader($user_id);
    }

	public function duozhuayu() {
		$data = GraspService::findDzyCart();
		if (!$data) {
			Log::error("获取dzy购物车失败");
			return false;
		}
		Log::info("App 请求成功");
		//    ix7QDEIK7YbcI3Wrc1hxVBHOELtiFkO6iRWwypCCH_c  书名：{{title.DATA}} 价格：{{price.DATA}} 链接：{{link.DATA}}
		foreach ($data as $d) {
			$title = $d['item']['book']['title'];
			$id = $d['item']['id'];
			if (Cache::has('book_' . $id)) {
				continue;
			}
			Log::info("购物车数据", ['title' => $title, 'type' => $d['type']]);
			if ($d['type'] == 'inStockCartBook') {
				$price = $d['item']['price'] / 100;
				//已到货
				Log::info("到货一件", $d);
				$data = ['title' => $title, 'price' => $price, 'link' => "https://www.duozhuayu.com/cart"];
				WechatService::sendMsg($data);
				Cache::put('book_' . $id, $d, now()->addMinutes(60));
				//锁定前加入购物车
				$bookGoods = $d['item']['book']['goods'][0];
				$carParam = [
					'condition' => $bookGoods['condition'],
					'flawFlag' => $bookGoods['flawFlag'],
					'flawReasons' => $bookGoods['flawReasons'],
				];
				GraspService::lockAddCart($id, $carParam);
				$lockRet = GraspService::lockDzyGood($id);
				Log::info("锁定商品结果", [$lockRet]);
				if ($lockRet) {
					$lockMsg = [
						'title' => '商品锁定成功:' . $title,
						'price' => $price,
						'link' => "https://www.duozhuayu.com/cart",
					];
					WechatService::sendMsg($lockMsg);
				}
			}
		}
               return "success";
	}
}
